/*
 * @Author: 王锴 1148506760@qq.com
 * @Date: 2024-01-14 17:28:58
 * @LastEditors: 王锴 1148506760@qq.com
 * @LastEditTime: 2024-01-16 14:23:25
 * @Description: 
 */
import React, { useState, useEffect } from 'react'
import { useNavigate } from "react-router-dom";
import styles from '../../style/login.module.less'
import content from '../../style/bigData/bigData.module.less'
import HeaderTop from "../../components/HeaderTop/HeaderTop";
import EchartsDom from '../../components/chartDomPie/chartDomPie';
import EchartsDomBar from '../../components/chartDomBar/chartDomBar';
import { message } from 'antd';
import { outDataByGoodsType, outDataByGoodsTypeZf, perMonthOut, homeGoodsData, operatorTJData } from '../../apis/bigDate'
import CanvasBackgroundImage from '../../components/CanvasPoints/CanvasPoints';

export default function BigData() {
    const [messageApi, contextHolder] = message.useMessage();
    const key = 'updatable';
    const navigate = useNavigate()
    const [title] = useState('农药监管平台');
    const [goodList, setGoodList] = useState([])
    const [centerWrap, setCenterWrap] = useState([
        { title: '全县经营主体（户）', num: "201326" },
        { title: '已接入监管（户）', num: "201326" },
        { title: '在册未缴费（户）', num: "201326" },
        { title: '已注销（户）', num: "201326" },
    ])
    const [bottomList, setBottomList] = useState([
        { title: '上季度销售量', num: "2652.32", url: '/CountyBusiness' },
        { title: '即将到期的库存', num: "2652.32" },
        { title: '过期处理', num: "2652.32" },
    ])

    const [rightOneList] = useState([
        { title: '统治防治', backImg: require("../../assets/images/bigData/1.png") },
        { title: '包装回收', backImg: require("../../assets/images/bigData/4.png") },
        { title: '执法监督', backImg: require("../../assets/images/bigData/3.png"), url: '/lawEnforcementSupervision' },
        { title: '技术培训', backImg: require("../../assets/images/bigData/2.png"), url: '/Teach' },
    ])
    const [chartsPie, setChartsPie] = useState([])
    const [chartDomBarYear, setChartDomBarYear] = useState([])
    const [chartDomBarNum, setChartDomBarNum] = useState([])

    const [salesWeight, setSalesWeight] = useState({ all_weight: 0, new_weight: 0 })
    useEffect(() => {
        getSalesData('')
        outDataByGoodsType_ZF()
        perMonthOutList()
        getHomeGoodsData()
        operatorTJGoodsData()

    }, []);
    // 农药销售数据
    const getSalesData = async (id) => {
        messageApi.open({
            key,
            type: 'loading',
            content: '数据加载中...',
        });
        const { data } = await outDataByGoodsType({ type_id: id, area_id: localStorage.getItem('areaId'), area_level: localStorage.getItem('areaLevel') })
        if (data.state === 1) {
            if (id === '') {
                setGoodList(data.typeList)
            } else {
            }
            setSalesWeight(data)
            messageApi.open({
                key,
                type: 'success',
                content: '数据加载完成!',
                duration: 2,
            });

        } else {
            messageApi.open({
                key,
                type: 'error',
                content: data.msg,
                duration: 2,
            });
        }
    };

    // 获得农药类型id
    const getTypeId = (id) => {
        getSalesData(id)
    };

    // 农药类型销售占比
    const outDataByGoodsType_ZF = async () => {
        const { data } = await outDataByGoodsTypeZf({ area_id: localStorage.getItem('areaId'), area_level: localStorage.getItem('areaLevel') })

        if (data.state === 1) {
            const newArray = []
            data.data.forEach(item => {
                newArray.push({ value: item.all_weight, name: item.type_name })
            })
            setChartsPie(newArray)
        } else {
            messageApi.open({
                key,
                type: 'error',
                content: data.msg,
                duration: 2,
            });
        }
    };
    // 每月农药销售总量变化
    const perMonthOutList = async () => {
        const { data } = await perMonthOut({ area_id: localStorage.getItem('areaId'), area_level: localStorage.getItem('areaLevel') })
        if (data.state === 1) {
            const newYear = []
            const newNum = []
            data.data.forEach(item => {
                newYear.push(item.out_time_str)
                newNum.push(item.all_weight)
            })
            setChartDomBarYear(newYear.reverse())
            setChartDomBarNum(newNum.reverse())
        } else {
            messageApi.open({
                key,
                type: 'error',
                content: data.msg,
                duration: 2,
            });
        }
    };
    // 销售库存数据
    const getHomeGoodsData = async () => {
        messageApi.open({
            key,
            type: 'loading',
            content: '数据加载中...',
        });
        const { data } = await homeGoodsData({ area_id: localStorage.getItem('areaId'), area_level: localStorage.getItem('areaLevel') })
        if (data.state === 1) {
            const newAry = bottomList.map(item => {
                switch (item.title) {
                    case '上季度销售量':
                        item.num = data.up_out
                        return item
                    case '即将到期的库存':
                        item.num = data.linqi_kc
                        return item
                    default:
                        item.num = data.guoqi_kc
                        return item
                }
            })
            setBottomList(newAry)
            messageApi.open({
                key,
                type: 'success',
                content: '数据加载完成!',
                duration: 2,
            });
        } else {
            messageApi.open({
                key,
                type: 'error',
                content: data.msg,
                duration: 2,
            });
        }
    };
    // 统计全县经营主体，已接入，未缴费，已注销
    const operatorTJGoodsData = async () => {
        const { data } = await operatorTJData({ area_id: localStorage.getItem('areaId'), area_level: localStorage.getItem('areaLevel') })
        if (data.state === 1) {
            const newArray = centerWrap.map(item => {
                switch (item.title) {
                    case '全县经营主体（户）':
                        item.num = data.operator
                        return item
                    case '已接入监管（户）':
                        item.num = data.normal
                        return item
                    case '在册未缴费（户）':
                        item.num = data.no_normal
                        return item
                    default:
                        item.num = data.no_operator
                        return item
                }
            })

            setCenterWrap(newArray)


        } else {
            messageApi.open({
                key,
                type: 'error',
                content: data.msg,
                duration: 2,
            });
        }
    };
    // 跳转到相应页面
    const gotoPage = (data) => {
        switch (data.title) {
            case '全县经营主体（户）':
                navigate('/SalesList');
                break;
            case '已接入监管（户）':
                navigate('/businessEntityAll');
                break;
            case '在册未缴费（户）':
                navigate('/UnpaidFees');
                break;
            default:
                navigate('/LoggedOut');
                break;
        }
    };
    // 全县上季度销售总量
    const goto = (e) => {
        if (e.title === '上季度销售量') {
            navigate(`${e.url}`);
        } else { }
    }
    const goTeach = (item) => {
        if (item.url !== undefined) {
            navigate(item.url);
        } else { }
    }
    return (
        <div className={styles.main}>
            {contextHolder}
            <HeaderTop title={title}></HeaderTop>
            <div className={content.content}>
                <div className={content.content_left}>
                    <div className={content.leftOne}>
                        <div className={content.bg}>
                            <span className={content.font}>农药经营示范店展示</span>
                            <span className={content.e_font}>Pesticide business store</span>
                        </div>
                        <div className={content.warp}>
                            <div className={content.warp_one}>
                                <div className={content.box_line}></div>
                            </div>
                        </div>
                    </div>
                    <div className={content.leftTwo}>
                        <div className={content.bg}>
                            <span className={content.font}>农药销售数据</span>
                            <span className={content.e_font}>Pesticide business store</span>
                        </div>
                        <div className={content.goodList}>
                            {
                                goodList.map(item => {
                                    return (
                                        <div key={item.id} className={content.good} onClick={() => getTypeId(item.id)}>{item.name}</div>
                                    )
                                })
                            }
                        </div>
                        <div className={content.bottom}>
                            <div className={content.bottom_left}>
                                <div className={content.box_line}></div>
                            </div>
                            <div className={content.bottom_right}>
                                <div className={content.bottom_box}>
                                    <img src={require('./../../assets/images/bigData/total.png')} className={content.bottom_img} alt="" />
                                    <div className={content.bottom_num}>
                                        <p className={content.title}>总销售量</p>
                                        <p><span className={content.yuan}>{salesWeight.all_weight}</span>kg</p>
                                    </div>
                                </div>
                                <div className={content.bottom_box}>
                                    <img src={require("./../../assets/images/bigData/year.png")} className={content.bottom_img} alt="" />
                                    <div className={content.bottom_num}>
                                        <p className={content.title}>今年销售量</p>
                                        <p><span className={content.yuan}>{salesWeight.new_weight}</span>kg</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div className={content.leftThree}>
                        <div className={content.bg}>
                            <span className={content.font}>农药类型销售占比%</span>
                            <span className={content.e_font}>Pesticide business store</span>
                        </div>
                        <div>
                            <EchartsDom chartsPie={chartsPie} wight='500px' height='230px'></EchartsDom>
                        </div>
                    </div>
                </div>
                <div className={content.content_center}>
                    <div className={content.center_top}>
                        {
                            centerWrap.map(e => {
                                return (
                                    <div className={content.center_wrap} key={e.title} onClick={() => gotoPage(e)}>
                                        <p className={content.center_title}>{e.title}</p>
                                        <p className={content.center_title} style={{ fontSize: '28px', marginTop: '8px' }}>{e.num}</p>
                                    </div>
                                )
                            })
                        }
                    </div>
                    <div style={{
                        width: '35vw',
                        display: 'flex',
                        margin: 'auto',
                        alignItems: 'center'
                    }}>
                        <CanvasBackgroundImage

                            imageUrl={sessionStorage.getItem('map')}

                        />


                    </div>

                    {/* <div className={content.total}>
                        <img src={require("./../../assets/images/bigData/total1.png")} alt="" className={content.totalImg} />
                    </div> */}
                    <div className={content.bottomLists}>
                        {
                            bottomList.map(e => {
                                return (
                                    <div className={e.title === '过期处理' ? `${content.error_} ${content.bottom_list}` :
                                        (e.id !== 1 ? `${content.bottom_list} ${content.warning_}` :
                                            `${content.bottom_list} ${content.warning_} ${content.noWarning}`)} onClick={() => goto(e)}>
                                        <p className={content.bottom_name}>{e.title}</p>
                                        <p className={content.bottom_name}>
                                            <span className={content.bottom_num}>{e.num}</span>
                                            <span style={{ color: 'gray' }}>kg</span>
                                        </p>
                                    </div>
                                )
                            })
                        }


                    </div>
                </div>
                <div className={content.content_right}>
                    <div className={content.rightOne}>
                        <div className={content.bg}>
                            <span className={content.font}>农药监管展示</span>
                            <span className={content.e_font}>Pesticide business store</span>
                        </div>
                        <div className={content.right_box}>
                            {
                                rightOneList.map(e => {
                                    return (
                                        <div className={content.right_wrap} key={e.backImg} onClick={() => goTeach(e)}>
                                            <div className={e.url === undefined ? `${content.warp_one}` : `${content.warp_one} ${content.show}`} style={{ backgroundImage: `url(${e.backImg})` }}>
                                                <div className={content.box_line}></div>
                                            </div>
                                            <p className={content.warp_oneTitle}>
                                                <img src={require("./../../assets/images/bigData/title_left.png")} alt="" style={{ verticalAlign: 'middle' }} />
                                                {e.title}
                                                <img src={require("./../../assets/images/bigData/title_right.png")} alt="" style={{ verticalAlign: 'middle' }} />
                                            </p>
                                        </div>
                                    )
                                })
                            }
                        </div>
                    </div>
                    <div className={content.rightTwo}>
                        <div className={content.bg}>
                            <span className={content.font}>每月农药销售总量变化</span>
                            <span className={content.e_font}>Pesticide business store</span>
                        </div>
                        <div>
                            <EchartsDomBar chartDomBarYear={chartDomBarYear} chartDomBarNum={chartDomBarNum} wight='567px' height='284px'></EchartsDomBar>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    )
}
